package com.doudou.dubbo.demo.service;

import com.doudou.dubbo.demo.api.GrettingServiceAsync;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.rpc.RpcContext;

/**
 * @author zhaozw
 * @version 1.0
 * @date 2025-07-22 19:20
 **/
public class GreetingServiceAsyncImpl implements GrettingServiceAsync {

    // 创建自定义线程池
    private final ThreadPoolExecutor bizThreadPool = new ThreadPoolExecutor(8, 16, 1, TimeUnit.MINUTES,
            new SynchronousQueue<>(), new NamedThreadFactory("biz-thread-pool"), new CallerRunsPolicy());

    @Override
    public CompletableFuture<String> sayHello(String name) {
        RpcContext context = RpcContext.getContext();
        return CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("async return");
            return "Hello " + name + " " + context.getAttachment("company");
        }, bizThreadPool);
    }
}
